package org.bot.plugin.web.source;

import org.bot.api.config.ClientConfig;
import org.bot.api.event.DataStorage;
import org.bot.api.source.SourceManage;
import org.bot.plugin.web.drive.LoadWeb;
import org.bot.plugin.web.util.WebApi;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author 沧月
 * @create 0001 2023/10/1 21:32
 * @description <description class purpose>
 */

@Component
public class SourceManageImpl implements SourceManage {
    static Logger logger = LoggerFactory.getLogger(SourceManageImpl.class);
    private BlockingQueue<WebDriver> CONNECTION_POOL;

    @Autowired
    LoadWeb loadWeb;


    @Autowired
    WebApi webApi;

    @Override
    public void releaseAllSource(DataStorage data) {
        try {
            data.getSource(WebDriver.class).forEach(this::releaseSource);
        } catch (Exception e) {
            logger.error("释放资源出现异常：", e);
        }
    }

    @Override
    public Object getSource() {
        if (CONNECTION_POOL == null) {
            int maxTask = ClientConfig.getBotConfig().getMaxTask();
            CONNECTION_POOL = new ArrayBlockingQueue<>(maxTask);
            for (int i = 0; i < maxTask; i++) {
                CONNECTION_POOL.add(loadWeb.load(ClientConfig.getBotConfig()));
            }
        }
        WebDriver driver;
        try {
            driver = CONNECTION_POOL.take();
            driver.getPageSource(); // 检查该对象是否能正常进行操作
            return driver;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (WebDriverException e) {
            //如果window窗口有问题那么重新创建一个
            return loadWeb.load(ClientConfig.getBotConfig());
        }
    }

    @Override
    public void releaseSource(Object source) {
        WebDriver webDriver = ((WebDriver) source);
        // 获取所有的窗口句柄
        Set<String> windowHandles = webDriver.getWindowHandles();
        // 遍历窗口句柄，关闭除最后一个之外的其他窗口
        for (String windowHandle : windowHandles) {
            if (!windowHandle.equals(webDriver.getWindowHandle())) {
                webDriver.switchTo().window(windowHandle);
                this.deleteData(webDriver);
                webDriver.close();
            }
        }

        // 切换回最后一个窗口
        webDriver.switchTo().window(webDriver.getWindowHandles().iterator().next());
        this.deleteData(webDriver);
        CONNECTION_POOL.offer(webDriver);
    }


    private void deleteData(WebDriver webDriver) {
        webDriver.manage().deleteAllCookies();
        webApi.script(webDriver, "localStorage.clear();");
    }
}
